// src/services/permissionService.ts

import type { UpdatePermissionsResponse, EditableUser } from '@/types/types';
import { BASE_URL } from '@/services/apiConfig';

export async function fetchAllUsers(skip = 0, limit = 10): Promise<EditableUser[]> {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('No token found');
    }

    const response = await fetch(
      `${BASE_URL}/users/list-users?skip=${skip}&limit=${limit}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      }
    );

    if (!response.ok) {
      throw new Error('Failed to fetch user list');
    }

    const result = await response.json();

    // Handle paginated response format
    const users = result.data?.users || result.users || [];

    const editableUser: EditableUser[] = users.map((user: { user_id?: number; id?: number; first_name: string; last_name: string; email: string; permission_ids?: number[] }, index: number) => ({
      userId: user.user_id || user.id || (skip + index + 1),
      firstName: user.first_name,
      lastName: user.last_name,
      email: user.email,
      permissions: user.permission_ids || [],
    }));

    return editableUser;
  } catch (error) {
    console.error('Fetch user list error:', error);
    return [];
  }
}

export const updateUserPermissions = async (
  email: string,
  permission_ids: number[]
): Promise<UpdatePermissionsResponse> => {
  const token = localStorage.getItem('token');
  if (!token) {
    throw new Error('No token found. Please login again.');
  }

  try {
    const response = await fetch(`${BASE_URL}/users/update-permissions`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ email, permission_ids }),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data?.message || 'Failed to update permissions');
    }

    return data as UpdatePermissionsResponse;
  } catch (err: unknown) {
    console.error('updateUserPermissions error:', err);
    const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred while updating permissions';
    throw new Error(errorMessage);
  }
};
